//
//  PickUpViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/9/13.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "PickUpViewController.h"
#import "UIColor+Hex.h"
#import <AliyunOSSiOS/OSSService.h>
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "ProblemViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapFoundationKit/AMapServices.h>
#import <AMapLocationKit/AMapLocationKit.h>
@interface PickUpViewController ()
@property NSMutableArray *imageUrl;
@property float lat;
@property float lon;
@end

@implementation PickUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _imageUrl = [[NSMutableArray alloc] init];
    
    self.note_text.delegate = self;
    [self.button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.button1.backgroundColor = [UIColor colorWithHexString:@"#ff7e00"];
    [self.button1.layer setBorderColor:[UIColor colorWithHexString:@"#ff7e00"].CGColor];
    [self.button1.layer setBorderWidth:1];
    [self.button1.layer setMasksToBounds:YES];
    
    [self.button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    [self.button2.layer setBorderColor:[UIColor grayColor].CGColor];
    [self.button2.layer setBorderWidth:1];
    [self.button2.layer setMasksToBounds:YES];
    [self.button2 addTarget:self action:@selector(problemClick) forControlEvents:UIControlEventTouchUpInside];

    
    
    
    [self.limitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    [self.limitBtn setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#55ff7e00"]] forState:UIControlStateSelected];
    [self.limitBtn addTarget:self action:@selector(limitClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.images = @[self.imageView1,self.imageView2,self.imageView3];
    self.photo_view1.tag = 0;
    self.photo_view2.tag = 1;
    self.photo_view3.tag = 2;
    
    [self.photo_view1 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.photo_view2 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    [self.photo_view3 addTarget:self action:@selector(callActionSheetFunc:) forControlEvents:UIControlEventTouchUpInside];
    
    [self initCompleteBlock];
    [self configLocationManager];
}
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    //[self.locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    //[self.locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)initCompleteBlock
{
    __weak PickUpViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            //如果为定位失败的error，则不进行annotation的添加
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        //得到定位信息，添加annotation
        if (location)
        {
            _lat = location.coordinate.latitude;
            _lon = location.coordinate.longitude;
        }
    };
}
-(void)problemClick{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    ProblemViewController *orderProblem = [story instantiateViewControllerWithIdentifier:@"problem_opp"];
    orderProblem.serviceNo = _serviceNo;
    orderProblem.popCount = 3;
    [self.navigationController pushViewController:orderProblem animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)button_click:(id)sender {
    
    UIView * view = sender;
    if(view.tag == 11){
        //返回键
        [self.navigationController popViewControllerAnimated:YES];
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    
    return theImage;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self.note_text resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    
    return YES;
}

/**
 @ 调用ActionSheet
 */
- (void)callActionSheetFunc:(UIControl *) controll{
    
    if (self.add_image_pos != controll.tag) {
        return;
    }
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",  nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",  nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 2) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //获得的图片
    UIImageView *imageView = self.images[self.add_image_pos];
    imageView.image = image;
    
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    [self uploadImage:imgData];
   
    
}


- (IBAction)view_touch:(id)sender {
    [self.view endEditing:YES];
}

-(void)uploadImage:(NSData *)img{
    
    
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:OOS_KEY_ID secretKey:OOS_KEY_SCERET];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-shanghai.aliyuncs.com" credentialProvider:credential];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    // 必填字段
    put.bucketName = OOS_KEY_BUCKET;
    
    NSString *filePath = [NSString stringWithFormat:@"%@.png",[self getUniqueStrByUUID]];
    put.objectKey = filePath;
    
    [_imageUrl addObject:[NSString stringWithFormat:@"http://%@.oss-cn-shanghai.aliyuncs.com/%@",OOS_KEY_BUCKET,filePath]];
    // put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
    put.uploadingData = img; // 直接上传NSData
    
    // 可选字段，可不设置
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
    // put.contentType = @"";
    // put.contentMd5 = @"";
    // put.contentEncoding = @"";
    // put.contentDisposition = @"";
    
    // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
    
    [MBProgressHUD showMessage:@"上传图片"];
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        if (!task.error) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                NSLog(@"上传图片结果22");
                [MBProgressHUD hideHUD];
                self.add_image_pos++;
                if (self.add_image_pos < 3) {
                    UIImageView *addimage = self.images[self.add_image_pos];
                    addimage.image = [UIImage imageNamed:@"add_image"];
                }
                NSLog(@"upload object success111!");
            });
            
            NSLog(@"upload object success222!");
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                
                [MBProgressHUD hideHUD];
                UIImageView *addimage = self.images[self.add_image_pos];
                addimage.image = [UIImage imageNamed:@"add_image"];
                [_imageUrl removeObjectAtIndex:_add_image_pos];
                NSLog(@"upload object success111!");
            });
        }
        
        
        return nil;
    }];
}
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}

-(void)limitClick{
    
   if (_imageUrl.count== 0 || _imageUrl .count < 2) {
        [MBProgressHUD showError:@"请上传至少两张照片"];
    }else{
        NSString *userId = [UserDefaultUtil getUserId];
        
        
        
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:userId forKey:@"identifier"];
        [dic setObject:_serviceNo forKey:@"serviceNo"];
        [dic setObject:@"完美" forKey:@"broken"];
        [dic setObject:_note_text.text forKey:@"notes"];
        
        
        [dic setObject:[NSString stringWithFormat:@"%f",_lon] forKey:@"lon"];
        [dic setObject:[NSString stringWithFormat:@"%f",_lat] forKey:@"lat"];
        [dic setObject:_imageUrl forKey:@"photos"];
        
        NSLog(@"%@",dic);
        HttpReauestParam *param = [[HttpReauestParam alloc] initWithData:@"order_delivery_operator" content:[self dictionaryToJson:dic] urlType:0];
        AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
        [MBProgressHUD showMessage:@"提货"];
        manage.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manage POST:param.SEVICE_URL parameters:param.param success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSDictionary * data = [NSJSONSerialization JSONObjectWithData:operation.responseObject options:0 error:nil];
            
            [MBProgressHUD hideHUD];
            
            if ([data[@"success"] boolValue]) {
                [MBProgressHUD showSuccess:@"提货成功"];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [MBProgressHUD showError:data[@"errorMsg"]];
            }
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"网络连接失败"];
        }];
    }
    
    
    
}

-(NSString*)dictionaryToJson:(id)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

@end
